"""Create a PKGBUILD file."""

import operator

from distutils.core import Command
from distutils.errors import DistutilsOptionError

TEMPLATE = '''
# Maintainer: %(maintainer_name)s <%(maintainer_mail)s>

pkgname=%(pkg_name)s
pkgver=%(version)s
pkgrel=%(release_version)s
pkgdesc=%(description)s
arch=('noarch')
url=%(url)s
license=('GPL')
depends=('python' %(depends)s)
source=(%(download_url)s)
md5sums=(%(pkg_md5)s)

build() {
  cd ${srcdir}
  python setup.py build
  python setup.py install --root=${pkgdir}
  install -Dm644 COPYING ${pkgdir}/usr/share/licenses/${pkgname}/COPYING
}
'''
PKG_NAME = {'argparse': 'argparse',
            'pyxdg': 'pyxdg',
            'pynotify': 'python-notify',
            'keyring': 'python-keyring',
            'oauth': 'python-oauth-svn'
            }

class pkgbuild(Command):

    # Brief (40-50 characters) description of the command
    description = "Create the distribution PKGBUILD file."

    # List of option tuples: long name, short name (None if no short
    # name), and help string.
    user_options = [('release=', 'r', "The release version"),
                    ('md5sum=', 's', "The package's md5sum")]


    def initialize_options (self):
        self.release = None
        self.md5sum = ''

    def finalize_options (self):
        if not self.release:
            raise DistutilsOptionError("required option 'release' not"
                                       "specified")

    def run (self):
        data = {'maintainer_name': repr(self.distribution.get_author()),
                'maintainer_mail': self.distribution.get_author_email(),
                'pkg_name': self.distribution.get_name().lower(),
                'version': self.distribution.get_version(),
                'release_version': self.release,
                'description': repr(self.distribution.get_description()),
                'url': repr(self.distribution.get_url()),
                'download_url': repr(self.distribution.get_download_url()),
                'pkg_md5': repr(self.md5sum),
                'depends': ' '.join(map(lambda dep: repr(PKG_NAME[dep]),
                                        self.distribution.get_requires()))
                }

        with open('PKGBUILD', 'w') as pkgbuild:
            pkgbuild.write(TEMPLATE % data)
